package com.csx.map;
/**
 * 基于链表实现的Map
 * @param <K>
 * @param <V>
 */
public class LinkedListMap<K, V> implements Map<K, V> {

    private class Node{
        /* 键*/
        public K key;

        /** 值  */
        public V value;

        /** 下一个节点  */
        public Node next;

        public Node( K key, V val, Node next){
            this.key = key;
            this.value = val;
            this.next = next;
        }

        public Node(K key){
            this(key,null,null);
        }

        public Node(){
            this(null,null,null);
        }
            @Override
            public String toString(){
                return key.toString();
            }
    }

    private Node dummyHead;

    private int size;

    public LinkedListMap(){
        dummyHead = new Node();
        size = 0;
    }

    private Node getNode(K key){
        Node cur = dummyHead.next;
        while(cur != null){
            if (cur.key.equals(key)){
                return cur;
            }
            cur = cur.next;
        }
        return null;
    }

    @Override
    public void add(K key, V value) {
        Node node = getNode(key);
        if (node == null){
            dummyHead.next = new Node(key,value,dummyHead.next);
            size++;
        }else{
            node.value = value;
        }
    }

    @Override
    public V remove(K key)  {

        Node prev = dummyHead;
        while(prev.next != null){
            if(prev.next.key.equals(key))
                break;
            prev = prev.next;
        }

        if(prev.next != null){
            Node delNode = prev.next;
            prev.next = delNode.next;
            delNode.next = null;
            size --;
            return delNode.value;
        }
            return null;
    }

    @Override
    public boolean contains(K key) {
        return  getNode(key) != null;
    }

    @Override
    public V get(K key) {
        Node node = getNode(key);
        return node == null ? null : node.value;
    }

    @Override
    public void set(K key, V value) throws IllegalAccessException {
        Node node = getNode(key);
        if (node == null){
           throw new IllegalAccessException(key + " 不存在");
        }else{
            node.value = value;
        }
    }

    @Override
    public int gitSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    public static void main(String[] args) throws IllegalAccessException {
        LinkedListMap<Integer,String> linkedListMap = new LinkedListMap<>();
        for (int i = 0; i < 5; i++) {
            linkedListMap.add(i,"user" + i);
        }
        linkedListMap.set(3,"csx");
        linkedListMap.remove(2);
        linkedListMap.get(3);
    }
}
